package com.wwt.server.imp;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wwt.server.mapper.MenuMapper;
import com.wwt.server.pojo.Admin;
import com.wwt.server.pojo.Menu;
import com.wwt.server.service.IMenuService;
import com.wwt.server.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Tao
 * @since 2021-12-05
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Resource
    private MenuMapper menuMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     *根据用户ID获取菜单列表
     * @return Role
     */
    @Override
    public List<Menu> getMenuByAdminId() {
        Admin user = (Admin)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer adminId = user.getId();
        //先去Redis找菜单列表
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        List<Menu> list = (List<Menu>)valueOperations.get("menu_" + adminId);
        if (CollectionUtils.isEmpty(list)){
            List<Menu> menuList = menuMapper.getMenuByAdminId(adminId);
            valueOperations.set("menu_"+adminId,menuList);
            return menuList;
        }
        return list;
    }
    /**
     * 根据角色获取菜单列表
     * @return
     */
    @Override
    public List<Menu> getMenuByRole() {
      return menuMapper.getMenuByRole();
    }

    /**
     * 获取所有的惨淡
     * @return List<Menu>
     */
    @Override
    public Result getAllMenus() {
        List<Menu> allMenus = menuMapper.getAllMenus();
        return Result.success("查询成功！",allMenus);
    }
}
